package com.example.e_comm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.service.PermissionService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/permission")
public class PermissionController {
    private final PermissionService permissionService;
    public PermissionController(PermissionService _permissionService) {
        this.permissionService = _permissionService;
    }
    @GetMapping("/list")
    public List<Permission> list() {
        return permissionService.list();
    }
    @GetMapping("/listByPage")
    public IPage<Permission> listByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ){
        return permissionService.page(new Page<>(pageNum, pageSize));
    }
    @GetMapping("/listByPageWithCondition")
         public IPage<Permission> listByPageWithCondition(
                @RequestParam(defaultValue = "1") Integer pageNum,
                @RequestParam(defaultValue = "10") Integer pageSize,
                @RequestParam(required = false) String keyword
    ){
        Page<Permission> page = new Page<>(pageNum, pageSize);
        return permissionService.getPermissionByPageWithCount(new Page<>(pageNum, pageSize), keyword);
    }
    @PostMapping("/create")
    public boolean create(@RequestBody Permission permission) {
        if (permissionService.count(
                new QueryWrapper<Permission>()
                        .eq("perm_name", permission.getPermName()))>0){
            return false;
        }
        if (permissionService.count(
                new QueryWrapper<Permission>()
                        .eq("perm_key", permission.getPermKey()))>0){
            return false;
        }
        return permissionService.save(permission);
    }
    @PostMapping("/delete/ids")
    public boolean delete(@RequestBody List<Long> ids) {
        return permissionService.removeByIds(ids);
    }
}
